/**
 * 包含多个action creater 函数的模块
 *  同步action：对象{type:'xxx',data:数据值}
 * 异步action: 函数dispatch=>{}
 */
import { SET_HEAD_TITLE, RECEIVE_USER, SHOW_ERROR_MSG ,RESET_USER} from "./action-types"
import { reqLogin } from "@/api"
import storageUtils from "@/utils/storageUtils";


/*
设置头部标题的同步action
 */
export const setHeadTitle = (headTitle) => ({ type: SET_HEAD_TITLE, data: headTitle })

//接收用户的同步action
export const receiveUser = (user) => ({ type: RECEIVE_USER, user })

//接收用户错误信息的同步action
export const showErrorMsg = (errorMsg) => ({ type: SHOW_ERROR_MSG, errorMsg })

/*
退出登陆的同步action
 */
export const logout = () => {
    // 删除local中的user
    storageUtils.removeUser()
    // 返回action对象
    return { type: RESET_USER }
}


/**
 * 登陆的异步action
 */
export const login = (username, password) => {
    return async dispatch => {
        //1.执行异步的action请求
        let result = await reqLogin(username, password)  //{status:0,data:user}  {status:1,msg:'xxxx'}
        //2.如果成功，分发同步的action
        if (result.data.status === 0) {
            const user = result.data.data
            //保存到local中
            storageUtils.saveUser(user);

            //接收分发用户同步action
            dispatch(receiveUser(user))
        } else {
            //3.如果失败了，分发失败同步的action
            const msg = result.data.msg
            dispatch(showErrorMsg(msg))
        }

    }
}